package org.breathe.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.breathe.protocal.Resp;
import org.breathe.protocal.decode.*;
import org.breathe.server.handler.RespCommandHandler;
import org.breathe.server.handler.RespDecoder;
import org.breathe.server.handler.RespEncoder;

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * @author: breathe
 * @createTime: 2025-05-14
 */
public class MiniRedisClient implements RedisClient {

    private String address;
    private Integer port;
    public MiniRedisClient(String address, Integer port) {
        this.address = address;
        this.port = port;
    }
    @Override
    public void start() {
        Bootstrap root = new Bootstrap();
        ChannelFuture bootstrap = root.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new RespDecoder());
                        channel.pipeline().addLast(new SimpleChannelInboundHandler<Resp>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext channelHandlerContext, Resp resp) throws Exception {
                                if (resp instanceof BulkString bulkString) {
                                    System.out.println(bulkString.getContent());
                                } else if (resp instanceof Errors errors) {
                                    System.out.println(errors.getContent());
                                } else if (resp instanceof RespInteger respInteger) {
                                    System.out.println(respInteger.getContent());
                                } else if (resp instanceof SimpleString simpleString){
                                    System.out.println(simpleString.getContent());
                                }
                            }
                        });
                        channel.pipeline().addLast(new RespEncoder());
                    }
                })
                .connect(address, port);
        Scanner scan = new Scanner(System.in);
        while (true) {
            Resp[] resps = Arrays.stream(scan.nextLine()
                            .split(" "))
                    .map(each -> new BulkString(each.getBytes()))
                    .toList()
                    .toArray(new Resp[0]);
            bootstrap.channel()
                    .writeAndFlush(new RespArray(resps));
        }
    }

    @Override
    public void stop() {
        System.out.println("OK");
    }
}
